package com.naizhuai.ui.management;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.naizhuai.MainActivity;
import com.naizhuai.R;
import com.naizhuai.network.exception.ApiException;
import com.naizhuai.network.exception.ServerException;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.adapter.ManageDividerItemDecoration;
import com.naizhuai.ui.adapter.management.StructureListAdapterHolder;
import com.naizhuai.ui.components.CircleImageView;
import com.naizhuai.ui.components.TipDialog;
import com.naizhuai.ui.entity.management.CompanyBean;
import com.naizhuai.ui.entity.management.ManagementMainMsgBean;
import com.naizhuai.Model.db.user.PersonUserBean;
import com.naizhuai.ui.entity.management.DepartmentBean;
import com.naizhuai.ui.management.presenter.CompanyManageDataApiStoreIml;
import com.naizhuai.ui.user.UserManageDataApiStoreIml;
import com.naizhuai.util.AddPersonUtils;
import com.naizhuai.util.ConstantsPersonResources;
import com.naizhuai.util.ConstantsState;
import com.naizhuai.util.DialogUtils;
import com.naizhuai.util.ImageUtils;
import com.naizhuai.util.IntentUtils;
import com.naizhuai.util.ListUtils;
import com.naizhuai.util.NaizhuAILog;
import com.naizhuai.util.RxUtils;
import com.naizhuai.util.SharedPreferenceUtil;
import com.naizhuai.util.ToastCompat;
import com.naizhuai.util.UidUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observer;
import rx.Subscription;

/**
 * 公司架构的展示列表（部门列表+没有进入部门的同事+搜索）
 */
public class CompanyTotalStructureActivity extends BaseActivity implements View.OnClickListener, StructureListAdapterHolder.OnItemClickListener {
    private static final String TAG = "CompanyTotalStructureActivity";

    @BindView(R.id.user_thumb)
    CircleImageView userThumb;
    @BindView(R.id.company_name)
    TextView companyName;
    @BindView(R.id.no_department_number)
    TextView personNumber;
    @BindView(R.id.add_department_layout)
    LinearLayout addDepartLayout;

    //公司公共的小组（部门）
    @BindView(R.id.company_structure_list)
    RecyclerView departList;
    private List<DepartmentBean> publicTeams;
    private StructureListAdapterHolder departAdapter;
    //没有公共部门的人员
    @BindView(R.id.person_list)
    RecyclerView personList;
    private List<PersonUserBean> oddPeople;
    private StructureListAdapterHolder oddPeopleAdapter;
    private Subscription userinfoSub;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBaseView();
        initData();
    }

    public static void startActivity(Context mContext) {
        IntentUtils.startActivity(mContext, CompanyTotalStructureActivity.class);
    }

    @Override
    protected void onResume() {
        super.onResume();
        requestData();
    }

    private void initBasicData() {
        publicTeams = new ArrayList<>();
        oddPeople = new ArrayList<>();
        setManageRecyclerView();
    }

    private void requestData() {
        Observer<ManagementMainMsgBean> observer = new Observer<ManagementMainMsgBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                hideWaitDialog();
                ApiException.showException(e, getActivityContext(), true);
            }

            @Override
            public void onNext(ManagementMainMsgBean result) {
                hideWaitDialog();
                publicTeams.clear();
                oddPeople.clear();
                publicTeams.addAll(result.getTeamList());
                oddPeople.addAll(result.getNoOrganizationList());
                personNumber.setText(String.format(getText(R.string.no_one_number).toString(), String.valueOf(oddPeople.size())));
                departAdapter.notifyDataSetChanged();
                oddPeopleAdapter.notifyDataSetChanged();
                NaizhuAILog.e(publicTeams.toString());
                NaizhuAILog.e(oddPeople.toString());
            }
        };
        Subscription sub = CompanyManageDataApiStoreIml.getInstance().getCompanyMainMsgByIds(getShareValue(CompanyBean.COMPANY_ID_KEY, "0")).subscribe(observer);
        showWaitDiaLog(sub);
    }

    private void initData() {
        initBasicData();
    }

    private void initBaseView() {
        initTitleView();
    }


    private void initTitleView() {
        String companyNameStr = getShareValue(CompanyBean.COMPANY_NAME_KEY, "");
        companyName.setText(companyNameStr);
        String userThumbUrl = getShareValue(PersonUserBean.USER_THUMB_URL_KEY, "");
        ImageUtils.glideThumbViewByUrl(this, userThumb, userThumbUrl);
    }

    private void setManageRecyclerView() {
        ManageDividerItemDecoration dividerDecoration = new ManageDividerItemDecoration(this, ManageDividerItemDecoration.VERTICAL_LIST, 5, true);
        dividerDecoration.setBaseFloat(0.3f);
        //团队的list
        departAdapter = new StructureListAdapterHolder(this, publicTeams, oddPeople, StructureListAdapterHolder.STRUC_TYPE_TEAM);
        departList.setNestedScrollingEnabled(false);
        departList.setHasFixedSize(true);
        departList.setLayoutManager(new LinearLayoutManager(this));
        departList.setItemAnimator(new DefaultItemAnimator());
        departList.addItemDecoration(dividerDecoration);
        departList.setAdapter(departAdapter);
        departAdapter.setOnItemClickListener(this);

        //成员的list
        oddPeopleAdapter = new StructureListAdapterHolder(this, publicTeams, oddPeople, StructureListAdapterHolder.STRUC_TYPE_PEOPLE);
        personList.setNestedScrollingEnabled(false);
        personList.setHasFixedSize(true);
        personList.setLayoutManager(new LinearLayoutManager(this));
        personList.setItemAnimator(new DefaultItemAnimator());
        personList.addItemDecoration(dividerDecoration);
        personList.setAdapter(oddPeopleAdapter);
        oddPeopleAdapter.setOnItemClickListener(this);
    }

    Observer<ManagementMainMsgBean> refreshObserver = new Observer<ManagementMainMsgBean>() {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            hideWaitDialog();
            if (e instanceof ApiException) {
                ApiException server = (ApiException) e;
                DialogUtils.showPromptDialog(CompanyTotalStructureActivity.this, server.getDisplayMessage());
            }
            DialogUtils.showPromptDialog(CompanyTotalStructureActivity.this, getResources().getText(R.string.sendfail).toString());
        }

        @Override
        public void onNext(ManagementMainMsgBean result) {
            hideWaitDialog();
            List<PersonUserBean> list = result.getNoOrganizationList();
            List<PersonUserBean> listA = ListUtils.getListsDifferData(oddPeople, list);
            oddPeople.addAll(listA);
            oddPeopleAdapter.notifyDataSetChanged();
        }
    };


    @Override
    public int getLayoutId() {
        return R.layout.activity_company_total_structure_layout;
    }


    @OnClick({R.id.back_icon, R.id.search_text, R.id.add_department_layout})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_icon:
                super.onBackPressed();
                break;
            case R.id.search_text:
                //跳转任务搜索界面
                IntentUtils.startActivity(this, CompanySearchActivity.class);
                break;
            case R.id.add_department_layout:
                //跳转新建部门界面
                showWaitDiaLog();
                if (!RxUtils.isNetRunning(userinfoSub)) {
                    userinfoSub = UserManageDataApiStoreIml.getInstance().getuserinfo().subscribe(new Observer<PersonUserBean>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                            hideWaitDialog();
                            if (e instanceof ApiException) {
                                ApiException ae = (ApiException) e;
                                DialogUtils.showPromptDialog(CompanyTotalStructureActivity.this, ae.getDisplayMessage());
                            }
                        }

                        @Override
                        public void onNext(PersonUserBean personUserBean) {
                            hideWaitDialog();
                            String companyPowerCode = personUserBean.getCompanyPowerCode();
                            if (companyPowerCode.equals(ConstantsState.COM_NORMAL_POWER_LEVEL)) {
                                DialogUtils.showPromptDialog(CompanyTotalStructureActivity.this, getString(R.string.create_department_power_error));
                            } else
                                IntentUtils.startActivity(CompanyTotalStructureActivity.this, CompanyAddPartActivity.class);
                        }
                    });
                }
                break;
        }
    }

    @Override
    public void onItemClick(View view, int position, int listType) {
        switch (listType) {
            case StructureListAdapterHolder.STRUC_TYPE_TEAM:
                //跳转部门详情界面
                String departmentId = publicTeams.get(position).getDepartmentId();
                IntentUtils.startActivityWithString(DepartmentBean.DEPARTMENT_ID_KEY, departmentId, this, CompanyTeamStructureActivity.class);
                break;
            case StructureListAdapterHolder.STRUC_TYPE_PEOPLE:
                //跳转个人信息界面
                PersonUserBean userBean = oddPeople.get(position);
                IntentUtils.startActivityWithString(PersonUserBean.USER_ID_KEY, userBean.getUid(), this, CompanyUserDetailsMsgActivity.class);
                break;
        }
    }
}
